<!-- 
requestAnimationFrame(callback): 本质上是为了解决定时器的时间间隔不稳定的问题;
    - 它采用了系统时间间隔
    - H5新增
    - 它的时间间隔是固定的 (大概17ms)
    --兼容性
 -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id="test" style="width: 0px; height: 12px; line-height: 12px; background-color: cornsilk;">0%</div>

    <div id="test2" style="width: 0px; height: 12px; line-height: 12px; background-color: cornsilk;">0%</div>

    <div id="t" style="width: 0px; height: 12px; line-height: 12px; background-color: cornsilk;">0%</div>

</body>
<script>
    var timer1 = requestAnimationFrame(()=>{
        console.log(1);
        console.log('timer:',timer1);
        // 取消定时器: cancelAniamtionFrame;
        cancelAnimationFrame(timer1);
    });
    console.log(timer1);

    // 兼容性:
    if(!window.requestAnimationFrame){
        requestAnimationFrame = function(fn,ms){
            setTimeout(fn,ms)
        }
    }

    // 使用:
    test.onclick = function(){
        var timer = setInterval(() => {
            if(parseInt(test.style.width)<500){
                test.style.width = parseInt(test.style.width)+5+'px';
                test.innerHTML = parseInt(test.style.width) / 5 + '%'
            }else{
                clearInterval(timer)
            }
        }, 17);
    }

    test2.onclick = function(){
        var timer = setTimeout(function fn(){
            if(parseInt(test2.style.width)<500){
                test2.style.width = parseInt(test2.style.width) + 5 + 'px';
                test2.innerHTML = parseInt(test2.style.width) / 5 + '%';
                timer = setTimeout(fn,17);
            }else{
                console.log('clear')
                clearTimeout(timer)
            }
        },17)
    }

    t.onclick = function (){
        let timer = requestAnimationFrame(function fn(){
         if(parseInt(t.style.width)<300){
           t.style.width = parseInt(t.style.width) + 3 + 'px';
           t.innerHTML = parseInt(t.style.width) / 3 + '%';
           timer = requestAnimationFrame(fn)  
         }else{
             cancelAnimationFrame(timer)
         }
        })
    }
    
</script>
</html>